<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 公开课 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-button type="primary" class="handle-del mr10" @click="addDialog">新增公开课</el-button>
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除 </el-button>
                <el-input v-model="query.keyword" placeholder="输入公开课名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column label="公开课封面" width="120">
                    <template slot-scope="scope">
                        <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id,'tableData')" alt="" class="info-image" />
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="公开课名称"></el-table-column>
                <el-table-column prop="description" label="公开课描述"></el-table-column>
                <el-table-column label="免费/付费">
                    <template slot-scope="scope">
                        <span style="color: #e65c5c">{{ scope.row.price == 0 ? '免费' : '¥ ' + scope.row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="view" label="浏览量"></el-table-column>
                <el-table-column prop="sales" label="订阅量"></el-table-column>
                <el-table-column prop="favorite" label="收藏量"></el-table-column>
                <el-table-column label="操作" width="440" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button @click="preview(scope.row.id, scope.row.title)" type="primary" size="mini">设置开播时间 </el-button>
                        <el-button @click="enter_anchor_dialog(scope.row.id, scope.row.status)" type="primary" size="mini">进入主播端</el-button>
                        <el-button @click="edit(scope.row)" type="success" size="mini">编辑</el-button>
                        <el-button @click="putOn(scope.row.id, scope.row.status)" type="warning" size="mini">{{ scope.row.status == 0 ? '上架' : '下架'}}</el-button>
                        <el-button @click="deleteRow(scope.row.id, scope.$index)" type="danger" size="mini">删除 </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.page"
                    :page-size="query.rows"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 新增公开课弹出框 -->
        <el-dialog title="新增/编辑公开课" @close="cancel" :visible.sync="showDialog" width="50%">
            <el-form ref="form" :rules="rules" :model="form" label-width="125px">
                <el-form-item label="公开课名称" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="公开课描述" prop="description">
                    <el-input type="textarea" :rows="2" v-model="form.description"> </el-input>
                </el-form-item>
                <el-form-item label="公开课封面">
                    <div class="avatar-uploader" @click="showUploadImage('livefm')">
                        <img v-if="form.cover" :src="form.cover" class="avatar" height="200px" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </div>
                    <div class="el-upload__tip">封面建议尺寸：800*600px，支持jpg、png</div>
                </el-form-item>
                <el-form-item label="分类" prop="category_id">
                    <el-select v-model="form.category_id" clearable placeholder="请选择视频分类">
                        <el-option-group v-for="group in options" :key="group.id" :label="group.title">
                            <el-option v-for="item in group._child" :key="item.id" :label="item.title" :value="item.id"> </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="会员专享">
                    <el-checkbox :true-label="1" :false-label="0" v-model="form.only_member">勾选后仅会员可订阅</el-checkbox>
                </el-form-item>
                <el-form-item label="是否付费">
                    <el-radio-group v-model="form.expense" @change="course_price">
                        <el-radio :label="0">免费</el-radio>
                        <el-radio :label="1">付费</el-radio>
                    </el-radio-group>
                    <div v-if="form.expense == 1">
                        <el-form-item label="商品价格">
                            <el-input v-model="form.price" class="showPay"></el-input><span>元</span>
                        </el-form-item>
                        <el-form-item label="划线价格">
                            <el-input v-model="form.marking_price" class="showPay"></el-input><span>元</span>
                        </el-form-item>
                    </div>
                </el-form-item>
                <el-form-item label="人数限制">
                    <el-input v-model="form.quantity"></el-input>
                </el-form-item>
                <!-- <el-form-item label="返还积分">
                    <el-input v-model="form.score"></el-input>
                </el-form-item> -->
                <el-form-item label="完整内容">
                    <quill-editor v-model="form.content" :options="editorOption" ref="myQuillEditor"></quill-editor>
                </el-form-item>
                <el-form-item label="选择讲师">
                    <el-button @click="chooseLecturer" type="primary" size="mini">选择讲师</el-button>
                    <el-table
                        :data="selectRowData"
                        v-if="selectRowData.length !== 0"
                        class="table"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                    >
                        <el-table-column label="讲师图片">
                            <template slot-scope="scope">
                                <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id,'selectRowData')" alt="" class="info-image" />                                
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="讲师姓名"></el-table-column>
                        <el-table-column prop="description" label="讲师描述"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <el-button @click="del_lecturer" type="danger" size="mini">移除讲师</el-button>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item>
                <el-form-item label="状态设置">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">立即上架</el-radio>
                        <el-radio :label="0">暂不上架</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save('form')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 讲师弹框 -->
        <el-dialog width="36%" title="选择讲师" @close="exit" :visible.sync="innerVisible" append-to-body>
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item>
                    <el-input v-model="query.keyword" placeholder="输入讲师姓名" class="handle-input mr10"></el-input>
                    <el-button type="primary" icon="el-icon-search" @click="lecturerSearch">搜索</el-button>
                </el-form-item>
                <el-table
                    :data="chooseLecturerTableData"
                    @row-click="chooseRow"
                    class="chooseLecturerTable"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                >
                    <el-table-column prop="name" label="讲师图片">
                        <template slot-scope="scope">
                            <!-- <img :src="scope.row.cover" alt="" class="info-image" /> -->
                            <img :src="scope.row.cover" @error="tabErrorPicture(scope.row.id,'chooseLecturerTableData')" alt="" class="info-image" /> 
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="讲师姓名"></el-table-column>
                    <el-table-column prop="description" label="讲师描述"></el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.page"
                        :page-size="query.rows"
                        :total="lecturerListTotal"
                        @current-change="lecturerPageChange"
                    >
                    </el-pagination>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="exit">关 闭</el-button>
            </span>
        </el-dialog>
        <!-- 预览弹框 -->
        <el-dialog :title="title" :visible.sync="previewDialogVisible" width="40%">
            <div class="preview">
                <div style="display: flex; justify-content: center; align-items: center">
                    <div style="flex: 1">
                        <h3 class="mb-10"><a href="/app/tuiliu.apk" target="_blank">手机直播APP点击下载</a></h3>
                        <img src="/image/downloadzhiboapp.png" width="150px" />
                    </div>
                    <div style="flex: 1">
                        <h3 class="mb-10"><a href="https://obsproject.com/zh-cn" target="_blank">PC端直播软件点击下载</a></h3>
                        <qriously value="https://obsproject.com/zh-cn" :size="150" :backgroundAlpha="1" />
                    </div>
                </div>
                <div style="display: flex; flex-direction: column; align-items: center">
                    <div>
                        设置开播时间
                        <el-date-picker
                            v-model="start_date"
                            type="date"
                            placeholder="选择日期"
                            class="ml-10 mt-10 mr-10"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd"
                        >
                        </el-date-picker>
                        <el-time-picker v-model="start_time" placeholder="任意时间点" style="width: 150px" value-format="HH:mm:ss">
                        </el-time-picker>
                    </div>
                    <div>
                        直播截止时间
                        <el-date-picker
                            v-model="end_date"
                            type="date"
                            placeholder="选择日期"
                            class="ml-10 mt-10 mr-10"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd"
                        >
                        </el-date-picker>
                        <el-time-picker v-model="end_time" placeholder="任意时间点" style="width: 150px" value-format="HH:mm:ss">
                        </el-time-picker>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="previewDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setDateTime">保存</el-button>
            </span>
        </el-dialog>
        <!-- 主播端弹框 -->
        <el-dialog title="选择开播方式" :visible.sync="anchorDialogVisible" width="30%">
            <!-- <div class="push-type-box"> -->
            <!-- <div class="push-type web">
                <img class="icon" src="https://wkt.twjha.cn/addons/muu_classroom/resource/images/push-web.png" />
                <h3 class="title">Web主播端</h3>
                <div class="desc">使用官方提供的Web端直播工具进行直播</div>
                <el-button @click="enter_anchor('web')" type="warning">进入直播间</el-button>
            </div> -->
            <div class="push-type obs">
                <div></div>
                <div style="color: red" v-if="!liveroomurl">请上架后再来查看直播房间地址</div>
                <qriously v-if="liveroomurl" :value="liveroomurl" :size="150" :backgroundAlpha="1" />
                <h3 class="title" v-if="liveroomurl">扫码进入直播间</h3>
                <div class="desc" v-if="liveroomurl">使用OBS/XSplit等第三方软件进行推流，适合专业直播经验主播</div>
                <el-button v-if="liveroomurl" @click="enter_anchor('obs')" type="warning">查看推流地址</el-button>
            </div>
            <!-- </div> -->
        </el-dialog>
        <uploadimage ref="uploadimagecom" v-on:childByImageValue="childByImageValue"></uploadimage>
    </div>
</template>

<script>
// 自定义工具栏配置
const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
    [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
    [{ direction: 'rtl' }], // text direction

    [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
    ['link', 'image', 'video'], // 对于图片上传这是重点
    ['clean'] // remove formatting button
];
import {
    classifyListData,
    lecturerListData,
    smallClassListData,
    addSmallClassData,
    delSmallClassData,
    showandupdateLiveTime
} from '../../api/index';
import uploadimage from '@/components/common/uploadimage.vue';
export default {
    name: 'lecturer',
    components: {
        uploadimage
    },
    data() {
        return {
            query: {
                status: 0,
                page: 1,
                rows: 4,
                keyword: ''
            },
            title: '',
            start_date: '',
            start_time: '',
            end_date: '',
            end_time: '',
            copy_value: '',
            id: '',
            form: {
                id: '',
                teacher_id: '',
                title: '',
                description: '',
                cover: '',
                category_id: '',
                only_member: '',
                expense: '',
                price: '',
                marking_price: '',
                quantity: '',
                // score: '',
                content: '',
                sort: '',
                status: 1
            },
            rules: {
                title: [
                    { required: true, message: '请输入公开课名称', trigger: 'blur' },
                    { min: 1, max: 30, message: '请输入1到30的字符', trigger: 'blur' }
                ],
                // description: [{ required: true, message: "请输入公开课描述", trigger: "blur" }],
                category_id: [{ required: true, message: '请选择分类', trigger: 'blur' }]
            },
            options: [],
            tableData: [],
            multipleSelection: [],
            delList: [],
            chooseLecturerTableData: [],
            selectRowData: [],
            showDialog: false,
            innerVisible: false,
            previewDialogVisible: false,
            anchorDialogVisible: false,
            pageTotal: 0,
            lecturerListTotal: 0,
            // 富文本自定义配置项
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions, // 工具栏
                        handlers: {
                            // 此处开始改写自带的图片上传
                            image: (value) => {
                                this.$refs.uploadimagecom.dialogVisible = true;
                                this.action = 'form_content_image';
                            }
                        }
                    },
                    // 调整图片大小
                    imageResize: {
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: ['Resize', 'DisplaySize', 'Toolbar']
                    }
                }
            },
            liveroomurl: '',
            errorProduct: require('@/assets/img/noProduct.jpg'), 
        };
    },
    created() {
        this.getData();
    },
    methods: {
        tabErrorPicture(id,data){    // 表格图文封面默认展示图
            let i = this[data].findIndex(v => v.id == id);
			this[data][i].cover = this.errorProduct;
        },
        getData() {
            smallClassListData(this.query).then((res) => {
                //console.log(res);
                this.tableData = res.data.list;
                this.pageTotal = res.data.count;
            });
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //批量删除
        delAllSelection() {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                const length = this.multipleSelection.length;
                let str = '';
                let strID = '';
                this.delList = this.delList.concat(this.multipleSelection);
                console.log(this.delList);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].title + ' ';
                    strID += this.multipleSelection[i].id + ',';
                }
                delSmallClassData({ id: strID.substring(0, strID.lastIndexOf(',')) }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success(`删除了${str}`);
                        this.multipleSelection = [];
                        this.getData();
                    }
                });
            });
        },
        // 搜索
        handleSearch() {
            this.$set(this.query);
            this.getData();
        },
        // 讲师搜索
        lecturerSearch() {
            this.chooseLecturer();
        },
        // 分页
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
        // 讲师分页
        lecturerPageChange(val) {
            this.$set(this.query, 'page', val);
            this.chooseLecturer();
        },
        // 封面上传
        handleCover(res) {
            if (res.code == 1) {
                this.form.cover = res.data.attachment;
            }
        },
        handleRemove(file, fileList) {
            // console.log(file, fileList);
        },
        course_price(v) {
            if (v == 0) {
                this.form.price = '';
                this.form.marking_price = '';
            }
        },
        //新增
        addDialog() {
            this.showDialog = true;
            this.selectRowData = [];
            classifyListData().then((res) => {
                this.options = res.data.list;
                // res.data.list.forEach((item) => {
                //     if (item._child) {
                //         console.log(item);
                //         this.options_child.push(item);
                //         console.log(this.options_child);
                //     }
                // });
            });
        },
        chooseLecturer() {
            this.innerVisible = true;
            lecturerListData(this.query).then((res) => {
                //console.log(res);
                this.chooseLecturerTableData = res.data.list;
                this.lecturerListTotal = res.data.count;
            });
        },
        chooseRow(row) {
            this.selectRowData = [];
            this.selectRowData.push(row);
            this.form.teacher_id = row.id;
            this.innerVisible = false;
        },
        del_lecturer() {
            this.selectRowData = [];
            this.form.teacher_id = '';
        },
        // 查看开播时间
        async preview(id, title) {
            this.previewDialogVisible = true;
            this.id = id;
            this.title = title;
            let res = await showandupdateLiveTime({ id, action: 'show' });
            if (res.code == 1) {
                this.start_date = res.data.startdate;
                this.start_time = res.data.starttime;
                this.end_date = res.data.enddate;
                this.end_time = res.data.endtime;
            } else {
                console.log('获取直播日期数据失败');
            }
        },
        clipboardSuccessHandler({ value, event }) {
            this.$message.success('复制成功');
        },
        clipboardErrorHandler({ value, event }) {
            console.log('复制失败', value);
        },
        enter_anchor_dialog(id, status) { //进入主播端
            this.anchorDialogVisible = true;
            this.id = id;
            if (status == 1) {
                let domainname = localStorage.getItem('domainname') ? localStorage.getItem('domainname') : 'xuejing';
                this.liveroomurl = this.$front.FrontUrl + '/xuejing/livecontent/' + domainname + '?id=' + id;
            } else {
                this.liveroomurl = '';
            }
        },
        async enter_anchor(push_type) { //查看推流地址
            this.anchorDialogVisible = false;
            let restime = await showandupdateLiveTime({ action: 'show', id:this.id }); //得到设置的开播时间
            if (restime.code == 1) {
                let intstarttime = restime.data.intstarttime;
                let intendtime = restime.data.intendtime;
                if (!intstarttime) {
                    this.$message.error('请设置开播时间');
                    return;
                }
                if (!intendtime) {
                    this.$message.error('请设置直播的结束时间');
                    return;
                }
            } else {
                this.$message.error('获取开播时间失败');
                return;
            }
            this.$router.push({ path: '/live_pushFlow', query: { push_type, id: this.id } });
        },
        //编辑
        edit(row) {
            //console.log(row);
            classifyListData().then((res) => {
                this.options = res.data.list;
            });
            this.selectRowData = [];
            this.showDialog = true;
            this.form = row;
            if(row.teacher_info){
            this.selectRowData.push(row.teacher_info);}
        },
        //上下架
        putOn(id, status) {
            this.$confirm(`确定${status == 0 ? '上架' : '下架'}吗！`, '提示', {
                type: 'warning'
            }).then(() => {
                addSmallClassData({ id: id, status: status == 0 ? 1 : 0 }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('操作成功');
                        this.getData();
                    }
                });
            });
        },
        //删除
        deleteRow(id, index) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                delSmallClassData({ id: id }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('删除成功');
                        this.tableData.splice(index, 1);
                        this.getData();
                    }
                });
            });
        },
        //取消
        cancel() {
            this.form = {};
            this.showDialog = false;
        },
        //关闭
        exit() {
            this.innerVisible = false;
        },
        //确定
        save(formName) {
            // let formData = new FormData();
            // formData.append('cover', this.cover);
            // formData.append('column', this.column);
            // formData.append("form", JSON.stringify(this.form));
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    addSmallClassData(this.form).then((res) => {
                        console.log(res);
                        if (res.code == 1) {
                            this.showDialog = false;
                            this.$message.success('操作成功');
                            this.getData();
                        }
                    });
                }
            });
        },
        showUploadImage(action) {
            //显示上传组件
            this.$refs.uploadimagecom.dialogVisible = true;
            this.action = action;
        },
        //确认按钮传值过来并赋值到form表单上
        childByImageValue: function (childValue) {
            if (this.action == 'livefm') {
                this.form.cover = childValue;
                //console.log(this.form.cover);
            } else if (this.action == 'form_content_image') {
                let quill = this.$refs.myQuillEditor.quill;
                // 获取光标所在位置
                let length = quill.getSelection().index;
                // 插入图片，res为服务器返回的图片链接地址
                quill.insertEmbed(length, 'image', childValue);
                quill.setSelection(length + 1);
            }
        },
        async setDateTime() {//设置开播时间
            let starttime = this.start_date + ' ' + this.start_time;
            let endtime = this.end_date + ' ' + this.end_time;
            let startDateM=getHTime(starttime);//得到开始时间毫秒数
            let endDateM=getHTime(endtime);  //得到开始毫秒数
            if(endDateM-startDateM<=0){
                this.$alert('截止时间必须大于开播时间', '消息提示', {confirmButtonText: '确定'});
                return;
            }
            if(endDateM-startDateM>3*3600*1000){ //初级会员3小时直播时间，预留接口
                 this.$alert('直播时间时长设置不能超过3小时！', '消息提示', {confirmButtonText: '确定'});
                 return;
            }
            let res = await showandupdateLiveTime({ id: this.id, starttime, endtime, action: 'update' });
            if (res.code == 1) {
                this.$message.success('直播时间设置成功');
                this.previewDialogVisible = false
            }else if(res.code==-2){
                this.$alert('直播时间时长设置不能超过3小时啊！', '消息提示', {confirmButtonText: '确定'});
            } 
            else {
                this.$message.error('设置直播时间失败');
            }
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    float: right;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.mr10 {
    margin-right: 10px;
}

.info-image {
    width: 80px;
    border-radius: 4px;
}

.showPay {
    width: 150px;
    margin-right: 10px;
    margin-bottom: 15px;
}

.chooseLecturerTable {
    cursor: pointer;
}

.preview {
    text-align: center;
}

/* 主播端弹框 */
.push-type-box {
    height: 280px;
}

.push-type {
    /* width: 50%;
    float: left; */
    text-align: center;
}

.push-type .icon {
    display: block;
    margin: 0 auto;
    width: 99px;
    height: 99px;
    overflow: hidden;
}

.push-type .title {
    margin-top: 20px;
    margin-bottom: 10px;
}

.push-type .desc {
    padding: 10px;
    margin-bottom: 20px;
    color: #999;
}
</style>

<style>
.el-upload--text {
    border: 0;
    height: 40px;
    text-align: left;
    overflow: unset;
}

.el-upload__tip {
    margin-top: 0;
}

.el-input-group__append {
    background: #e6a23c;
}

.el-input-group__append span {
    color: #fff;
}

.ql-container {
    height: 200px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 375px !important;
    text-align: center;
}

.avatar-uploader:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
}

.avatar {
    width: 100%;
    display: block;
}
</style>


